package com.fqyd.campustransaction.controller;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.fqyd.campustransaction.model.Task;
import com.fqyd.campustransaction.model.Type;
import com.fqyd.campustransaction.model.User;
import com.fqyd.campustransaction.utils.Tools;

/**
 * 任务
 */
@Controller
@Scope(value = "prototype")
public class TaskController extends BaseController {

	@RequestMapping("admin_task_list")
	public String taskList(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("loguser");
		user = userService.getById(user.getId());
		List<Task> tasks = taskService.getByUserId(user.getId());
		List<Type> types = typeService.getAll();
		request.setAttribute("tasks", tasks);
		request.setAttribute("types", types);
		return "admin/task_list";
	}

	@RequestMapping("admin_task_add")
	public String taskAdd(HttpServletRequest request, RedirectAttributes attributes) {
		String typeId = request.getParameter("type_id");
		String name = request.getParameter("name");
		String price = request.getParameter("price");
		String description = request.getParameter("description");
		String picture = "/page/static/images/task/default.png";
		List<Type> types = typeService.getAll();
		request.setAttribute("types", types);
		if (name == null || name.isEmpty()) {
			return "admin/task_add";
		}
		User user = (User) request.getSession().getAttribute("loguser");
		user = userService.getById(user.getId());
		String taskId = Tools.createID();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) (request);
		MultipartFile file = multipartRequest.getFile("file");
		if (!file.getOriginalFilename().isEmpty()) {
			String filePath = request.getServletContext().getRealPath("/") + "page/static/images/task/";
			String fileName = taskId + "_" + file.getOriginalFilename();
			File destFile = new File(filePath, fileName);
			try {
				file.transferTo(destFile);
			} catch (IOException e) {
				e.printStackTrace();
			}
			picture = "/page/static/images/task/" + fileName;
		}
		Task task = new Task();
		task.setId(taskId);
		task.setTypeId(typeId);
		task.setUserId(user.getId());
		task.setName(name);
		task.setPicture(picture);
		task.setPrice(BigDecimal.valueOf(Double.valueOf(price)));
		task.setDescription(description);
		task.setStatus("待审核");
		taskService.add(task);
		attributes.addFlashAttribute("message", "操作成功：发布任务（" + task.getName() + "）成功，等待管理员审核");
		return "redirect:admin_task_list.do";
	}

	@RequestMapping("admin_task_modify")
	public String taskModify(HttpServletRequest request) {
		String taskId = request.getParameter("task_id");
		if (Tools.isEmpty(taskId)) {
			return "redirect:admin_task_list.do";
		}
		Task task = taskService.getById(taskId);
		if (task == null) {
			return "redirect:admin_task_list.do";
		}
		List<Type> types = typeService.getAll();
		request.setAttribute("types", types);
		request.setAttribute("task", task);
		return "admin/task_modify";
	}

	//Du:搜索任务
	@RequestMapping("admin_task_search")
	public String goods(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("loguser");//从Session中获取用户对象
		String userId = user.getId();//提取用户ID
		String name = request.getParameter("taskName");//从前台请求中获取任务名称
		name = "%" + name + "%";//为数据库模糊查询更改格式
		Task task = new Task();
		task.setUserId(userId);
		task.setName(name);
		List<Task> tasks = taskService.getByUserAndOrderId(task);//查询对应用户的任务并返回
		List<Type> types = typeService.getAll();
		request.setAttribute("tasks", tasks);
		request.setAttribute("types", types);
		return "admin/task_list";
	}

	//Du:删除任务
	@RequestMapping("admin_task_delete")
	public String taskModify(HttpServletRequest request, RedirectAttributes attributes) {
		String taskId = request.getParameter("task_id");//从前台接收任务ID
		if (Tools.isEmpty(taskId)) {//如果接收的任务ID为空则返回刷新页面
			return "redirect:admin_task_list.do";
		}
		Task task = taskService.getById(taskId);//从数据库中根据任务ID查询任务
		if (task == null) {//如果数据库中无此任务则返回刷新页面
			return "redirect:admin_task_list.do";
		}
		if(!task.getStatus().equals("已接取")){//如果任务已被接收则不可删除
			task.setStatus("已删除");//删除任务
			taskService.update(task);
			attributes.addFlashAttribute("message", "操作成功：删除任务成功");
		}
		return "redirect:admin_task_list.do";
	}

	@RequestMapping("admin_task_modify_save")
	public String taskModifySave(HttpServletRequest request, RedirectAttributes attributes) {
		String taskId = request.getParameter("task_id");
		String typeId = request.getParameter("type_id");
		String name = request.getParameter("name");
		String price = request.getParameter("price");
		String description = request.getParameter("description");
		if (Tools.isEmpty(taskId)) {
			return "redirect:admin_task_list.do";
		}
		Task task = taskService.getById(taskId);
		if (task == null) {
			return "redirect:admin_task_list.do";
		}
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) (request);
		MultipartFile file = multipartRequest.getFile("file");
		if (!file.getOriginalFilename().isEmpty()) {
			String filePath = request.getServletContext().getRealPath("/") + "page/static/images/task/";
			String fileName = taskId + "_" + file.getOriginalFilename();
			File destFile = new File(filePath, fileName);
			try {
				file.transferTo(destFile);
			} catch (IOException e) {
				e.printStackTrace();
			}
			task.setPicture("/page/static/images/task/" + fileName);
		}
		if ("审核驳回".equals(task.getStatus())) {
			task.setStatus("待审核");
		}
		task.setTypeId(typeId);
		task.setName(name);
		task.setPrice(BigDecimal.valueOf(Double.valueOf(price)));
		task.setDescription(description);
		taskService.update(task);
		attributes.addFlashAttribute("message", "操作成功：修改任务（" + task.getName() + "）成功");
		return "redirect:admin_task_list.do";
	}
}
